<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Web Solutions
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: vshoor $ ($Date: 2006/04/11 20:58:15 $)
// $RCSfile: impex.tickets.php,v $ : $Revision: 1.9 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================

if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

require_once ("./modules/tickets/tickets.php");

/**
* Return the Total Pages for this Plugin
*/
function getPluginTotalPages1()
{
	global $impexDB;

	$_total = $impexDB->queryFetch("SELECT COUNT(*) AS totaltickets FROM `asTickets`;");
	$finaltotal = intval($_total["totaltickets"]);

	$totalpages = ceil($finaltotal/IMPEX_PASS)+1;

	return $totalpages;
}

/**
* Run the specific page for plugin
*/
function runPluginPage1($page)
{
	global $dbCore, $impexDB, $_IMPEXHASH, $_SWIFT;

	// Import Predefined Replies
	if ($page == 1)
	{
		$predefinedcategoryid = _impexInsertPredefinedCategory(0, "Impex");

		$predefinedreplies = array();
		$impexDB->query("SELECT * FROM `asPredefinedReplies` ORDER BY `id` ASC;");
		while ($impexDB->nextRecord())
		{
			_impexProcessSlashVariables($impexDB->Record);

			$predefinedreplies[$impexDB->Record["id"]] = $impexDB->Record;
		}

		foreach ($predefinedreplies as $key=>$val)
		{
			_impexInsertPredefinedReply($predefinedcategoryid, $val["subject"], $val["contents"]);

			displayStatus("Imported Predefined Reply: ".htmlspecialchars($val["subject"]));
		}

	// Import Tickets
	} else {
		// Import Tickets! The big tough crap function.
		if (empty($_POST["ticketstartat"]))
		{
			$_startat = 1;
		} else {
			$_startat = intval($_POST["ticketstartat"]);
		}

		$ticketidlist = $ticketlist = $ticketidcharlist = $ticketidpointer = $newticketpointer = array();

		// First get all the tickets
		$impexDB->query("SELECT * FROM `asTickets` WHERE `id` >= '". intval($_startat) ."' ORDER BY `id` ASC LIMIT ". intval(IMPEX_PASS) .";");
		while ($impexDB->nextRecord())
		{
			_impexProcessSlashVariables($impexDB->Record);

			$ticketidlist[] = $impexDB->Record["id"];
			$ticketidcharlist[] = $impexDB->Record["ticketid"];
			$ticketidpointer[$impexDB->Record["ticketid"]] = $impexDB->Record["id"];
			$ticketlist[$impexDB->Record["id"]] = $impexDB->Record;
			$ticketlist[$impexDB->Record["id"]]["posts"] = array();
			$lastticketid = $impexDB->Record["id"];
		}

		// Now load in the ticket data first
		$impexDB->query("SELECT * FROM `asTicketsData` WHERE `ticketidno` IN (". buildIN($ticketidlist) .");");
		while ($impexDB->nextRecord())
		{
			_impexProcessSlashVariables($impexDB->Record);

			$_ticket = &$ticketlist[$impexDB->Record["ticketidno"]];
			$_ticket["posts"][0]["dateline"] = $_ticket["dateline"];
			$_ticket["posts"][0]["fullname"] = $_ticket["fullname"];
			$_ticket["posts"][0]["email"] = $_ticket["email"];
			$_ticket["posts"][0]["subject"] = $_ticket["subject"];
			$_ticket["posts"][0]["ipaddress"] = $_ticket["ipaddress"];
			$_ticket["posts"][0]["creator"] = $_ticket["creator"];
			$_ticket["posts"][0]["contents"] = $impexDB->Record["contents"];
		}

		// Now load in stuff from asTicketReply table
		$impexDB->query("SELECT * FROM `asTicketReply` WHERE `parentid` IN (". buildIN($ticketidcharlist) .");");
		while ($impexDB->nextRecord())
		{
			_impexProcessSlashVariables($impexDB->Record);

			$ticketidno = intval($ticketidpointer[$impexDB->Record["parentid"]]);
			$_ticket = &$ticketlist[$ticketidno];
			$_ticket["posts"][$impexDB->Record["id"]] = $impexDB->Record;
		}

		// By now, almost all data should be loaded.. insert the tickets first
		foreach ($ticketlist as $key=>$val)
		{
			$newdepartmentid = intval($_IMPEXHASH["departmentpointer"][$val["depid"]]);
			if (empty($newdepartmentid))
			{
				displayStatus("<font color='red'>WARNING:</font> Ticket ".$val["ticketid"]." does not have a valid department. Ignoring.");
			} else {
				$ticketid = _impexInsertTicket($val["ticketid"], $newdepartmentid, intval($val["type"]), intval($val["level"]), "0", "0", "0", "0", $val["fullname"], $val["email"], $val["lrby"], $val["subject"], $val["dateline"], $val["lrdateline"], $val["replies"], iif($val["creator"]=="customer", POST_CLIENT, POST_STAFF));

				$firstpostid = $lastpostid = 0;

				foreach ($val["posts"] as $postkey=>$postval)
				{
					$_ticketpostid = _impexInsertTicketPost($ticketid, $postval["dateline"], "0", $postval["fullname"], $postval["email"], "", $postval["subject"], $postval["ipaddress"], iif($postval["creator"]=="customer", POST_CLIENT, POST_STAFF), $postval["isemailed"], 0, $postval["contents"]);
					$lastreplier = $postval["fullname"];
					if (empty($firstpostid))
					{
						$firstpostid = $_ticketpostid;
					}
					$lastpostid = $_ticketpostid;
				}

				$dbCore->query("UPDATE `". TABLE_PREFIX ."tickets` SET `lastreplier` = '". $dbCore->escape(iif(empty($lastreplier), $val["fullname"], $lastreplier)) ."', `firstpostid` = '". intval($firstpostid) ."', `lastpostid` = '". intval($lastpostid) ."' WHERE `ticketid` = '". intval($ticketid) ."';");
				$newticketpointer[$val["ticketid"]] = $ticketid;

				displayStatus("Imported Ticket: ".$val["ticketid"]);
			}
		}

		unset($ticketlist);
		// Time to import all ticket notes...
		$notes = array();
		$impexDB->query("SELECT * FROM `asTicketNotes` WHERE `parentid` IN (". buildIN($ticketidcharlist) .");");
		while ($impexDB->nextRecord())
		{
			_impexProcessSlashVariables($impexDB->Record);

			$notes[$impexDB->Record["id"]] = $impexDB->Record;
		}

		foreach ($notes as $key=>$val)
		{
			$newstaffid = intval($_IMPEXHASH["staffpointer"][$val["userid"]]);

			$ticketid = $newticketpointer[$val["parentid"]];
			_impexInsertTicketNote($ticketid, NOTE_TICKET, 0, $newstaffid, $val["dateline"], $val["contents"]);

			_impexTagTicketHasNotes($ticketid);
		}
		unset($notes);

		// Now import all flags
		$flags = array();
		$impexDB->query("SELECT * FROM `asTicketFlagged` WHERE `parentid` IN (". buildIN($ticketidcharlist) .");");
		while ($impexDB->nextRecord())
		{
			_impexProcessSlashVariables($impexDB->Record);

			$flags[$impexDB->Record["id"]] = $impexDB->Record;
		}

		foreach ($flags as $key=>$val)
		{
			$newstaffidfor = intval($_IMPEXHASH["staffpointer"][$val["userfor"]]);
			$newstaffidby = intval($_IMPEXHASH["staffpointer"][$val["userby"]]);

			$ticketid = $newticketpointer[$val["parentid"]];
			_impexInsertTicketNote($ticketid, NOTE_TICKET, $newstaffidfor, $newstaffidby, DATENOW, $val["contents"]);

			_impexTagTicketHasNotes($ticketid);
		}
		unset($flags);

/*		// Import Custom Fields
		$cfieldnotes = array();
		$impexDB->query("SELECT * FROM `asFieldData` WHERE `parentid` IN (". buildIN($ticketidlist) .");");
		while ($impexDB->nextRecord())
		{
			_impexProcessSlashVariables($impexDB->Record);

			$cfieldnotes[$impexDB->Record["parentid"]] .= $impexDB->Record["title"].":".$impexDB->Record["valuem"]."<BR />";
		}

		foreach ($cfieldnotes as $key=>$val)
		{
			$ticketid = $key;
			_impexInsertTicketNote($ticketid, NOTE_TICKET, 0, "0", DATENOW, $val);

			_impexTagTicketHasNotes($ticketid);
		}*/

		$_SWIFT["ticketstartat"] = $lastticketid+1;
	}
}
?>